package com.qltv.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.qltv.service.CoreService;
import com.qltv.utils.SignUtil;
/**
 * 
 * 类名：CoreServlet
 * 描述：接收微信服务器传来的消息
 * @author telnet
 * 创建时间：2018年1月10日
 */
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 5041430577316726666L;
	private static final Logger logger = Logger.getLogger(CoreServlet.class);
	/**
	 * 确认请求来自微信服务器
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//微信加密签名
		String signature = request.getParameter("signature");
		//时间戳
		String timestamp = request.getParameter("timestamp");
		//随机数
		String nonce = request.getParameter("nonce");
		//随机字符串
		String echostr= request.getParameter("echostr");
		
		PrintWriter out = response.getWriter();
		//通过校验
		if(SignUtil.checkSignature(signature, timestamp, nonce)){
			out.print(echostr);
			//System.out.println("[[["+echostr+"]]]");
		}
		out.close();
		out = null;
	}
	
	/**
	 * 处理微信服务器发来的消息
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置响应和请求编码都为utf-8
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//调用核心业务类接收消息、处理消息
		String respXml = CoreService.processRequest(request);
		//String respXml = "<xml><ToUserName><![CDATA[oegn_t_Z6PMYOSXwBk02YWboK7xo]]></ToUserName> <FromUserName><![CDATA[gh_0b8f46a6520a]]></FromUserName> <CreateTime>1515644183</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[这是一个文本消息]]></Content> <MsgId>6509642198913264310</MsgId> </xml>";
		logger.info("最终处理好的信息是这个--->"+respXml);
		PrintWriter out = response.getWriter();
		out.print(respXml);
		out.close();
		
		
	}
}
